package club.ruanx.movie.aop.aspect;

import club.ruanx.movie.common.aop.annotation.DeleteOnSolr;
import club.ruanx.movie.entity.Movie;
import club.ruanx.movie.util.SolrUpdater;
import club.ruanx.search.feign.client.SolrMovieServiceClient;
import club.ruanx.util.AspectUtils;
import club.ruanx.util.SpelUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

/**
 * @author 阮胜
 * @date 2019/2/15 17:31
 */
@Component
@Aspect
@Slf4j
public class SolrMovieAspect {

    private final SolrUpdater solrUpdater;
    private final SolrMovieServiceClient solrMovieServiceClient;

    public SolrMovieAspect(SolrUpdater solrUpdater, SolrMovieServiceClient solrMovieServiceClient) {
        this.solrUpdater = solrUpdater;
        this.solrMovieServiceClient = solrMovieServiceClient;
    }

    @AfterReturning(pointcut = "@annotation(club.ruanx.movie.common.aop.annotation.SaveOnSolr)", returning = "movie")
    public void save(Movie movie) {
        solrUpdater.updateToSolrServer(movie);
    }

    @Before("@annotation(deleteOnSolr)")
    public void deleteOnSolr(JoinPoint joinPoint, DeleteOnSolr deleteOnSolr) {
        String[] methodParamNames = AspectUtils.getMethodParamNames(joinPoint);
        String movieId = SpelUtils.parseExpression(deleteOnSolr.key(), methodParamNames, joinPoint.getArgs());
        solrMovieServiceClient.delete(movieId);
    }
}
